package com.kook.ball.security;

import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class HashingProvider {
	private static byte[] base64ToByte(String data) throws IOException {
		BASE64Decoder decoder = new BASE64Decoder();
		return decoder.decodeBuffer(data);
	}

	private static String byteToBase64(byte[] data) {
		BASE64Encoder endcoder = new BASE64Encoder();
		return endcoder.encode(data);
	}

	public static String getSalt() throws NoSuchAlgorithmException {
		SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
		byte[] salt = new byte[8];
		random.nextBytes(salt);
		return byteToBase64(salt);
	}

	public static String hashSHA256WithSalt(String password, String salt)
			throws IOException, NoSuchAlgorithmException {
		byte[] bPassword = base64ToByte(password);
		byte[] bSalt = base64ToByte(salt);
		MessageDigest digest = MessageDigest.getInstance("SHA-256");
		digest.reset();
		digest.update(bSalt);
		byte[] bHashed = digest.digest(bPassword);
		String hashString = byteToBase64(bHashed);
		return hashString;
	}
}
